import axios from "axios";
import config from "@/config.js"

let requestPre = ""

//初始化axios
if (process.env.NODE_ENV == 'development') {
    requestPre= 'http://localhost:50000/api'
} else {
    requestPre= '/api'
}

axios.defaults.baseURL = requestPre

function addToken(url) {
  let back = url;
  let _token = localStorage.getItem("_token") || "token";

  if (url.indexOf("?") != -1) {
    back = url + "&_token=" + _token;
  } else {
    back = url + "?_token=" + _token;
  }

  return back;
}

function post(url, param = {}) {
    url = addToken(url);
    return new Promise((succHandle, errHandle)=>{
        axios.post(url,param).then((res)=>{
            const resp = res.data
            if(resp.errcode == 0){
                succHandle(resp.data)
            }else{
                alert(resp.errmsg, resp.errcode)
            }
        }).catch(function (err) {
            errHandle(err);
        })
    })
}

function get(url, param = {}) {
    url = addToken(url);
    param['size'] = config.ps
    return new Promise((succHandle, errHandle)=>{
        axios({
        method: "get",
        url: url,
        params: param,
        responseType: "json"
      }).then((res)=>{
            const resp = res.data
            if(resp.errcode == 0){
                succHandle(resp.data)
            }else{
                alert(resp.errmsg, resp.errcode)
            }
        }).catch(function (err) {
            errHandle(err);
        })
      })
}

export { post, get, addToken };

